// pages/launch/index.js
wx.cloud.init();
const app = getApp();
const db = wx.cloud.database();
var util = require('../../utils/util.js');
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';

const settime = {
  月: ['0','1', '2', '3', '4', '5','6'],
  天: ['0','1', '2', '3', '4', '5','6','7', '8', '9', '10', '11','12','13', '14', '15', '16', '17','18','19', '20', '21', '22', '23','24','25', '26', '27', '28', '29','30'],
  时: ['0','1', '2', '3', '4', '5','6','7', '8', '9', '10', '11','12','13', '14', '15', '16', '17','18','19', '20', '21', '22', '23','24']
  // 分: ['0','1', '2', '3', '4', '5','6','7', '8', '9', '10', '11','12','13', '14', '15', '16', '17','18','19', '20', '21', '22', '23','24','25', '26', '27', '28', '29','30','31', '32', '33', '34', '35','36','37', '38', '39', '40', '41','42','43', '44', '45', '46', '47','48','49', '50', '51', '52', '53','54','55', '56', '57', '58', '59'],
};

// import Vue from 'vue';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showpop: false,
    overmonths:0,
    overdays:0,
    overhours:0,
    overtime: "请选择倒计时时间",
    columns: [
      {
        values: (settime['月']),
        className: 'column1',
      },
      {
        values: settime['天'],
        className: 'column2'
      },
      {
        values: settime['时'],
        className: 'column3'
      }
    ],
    shows: false, //控制下拉列表的显示隐藏，false隐藏、true显示
    selectDatas: [
      {
        title: '竞赛'
      },
      {
        title: '拼车'
      },
      {
        title: '运动'
      },
      {
        title: '旅行'
      }
      ,
      {
        title: '其他'
      }
    ], //下拉列表的数据
    indexs: 0, //选择的下拉列 表下标,
    fileList: [],
    location:"",
    content: '',
    topic: ''
  },
  onConfirm(event) {
    const { picker, value, index } = event.detail;
    this.setData({
      overtime:this.data.overmonths+'月'+this.data.overdays+'天'+this.data.overhours+'时'+'后结束'
    })

    this.onClose()
  },

  onCancel() {
    
    Toast('取消');
    this.onClose()
  },
  onChange(event) {
    const { picker, value, index } = event.detail;
    // Toast(`当前值：${value}`);
    this.setData({
      overmonths:value[0],
      overdays:value[1],
      overhours:value[2],
    })
  },
  // 获取位置信息
  getLocation(){
    wx.chooseLocation({
      success: (res)=>{
        this.setData({
          location: res.name
        });
      },
      fail:(reason)=>{
        console.log("调用位置信息失败了")
        console.log(reason)
      }
    })
  },

  showPopup() {//展示弹出层 即选择日期
    // console.log(this.data.overtime);
    // console.log(typeof(this.data.overtime));
    this.setData({ showpop: true });
  },

  onClose() {//关闭弹出层
    this.setData({ showpop: false });
  },

  handleTopic(e){
    this.setData({
      topic: e.detail
    });
  },
  // 正文表单输入
  handleInput(e){
    let content = e.detail.value;
    this.setData({
      content
    })
  },

  // 点击下拉显示框
  selectTaps() {
    this.setData({
      shows: !this.data.shows,
    });
  },
  // 点击下拉列表
  optionTaps(e) {
    let Indexs = e.currentTarget.dataset.index; //获取点击的下拉列表的下标
    this.setData({
      indexs: Indexs,
      shows: !this.data.shows
    });
  },
  
  afterRead(event) {
    const { file } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    // console.log(file);
    wx.getFileSystemManager().readFile({
      filePath: file.url,
      success: async buffer => {
        let res = await wx.cloud.callFunction({
          name: 'contentCheck',
          data: {
            img: buffer.data
          }
        })
        // console.log(res);
        if(res.result.imageR.errCode===87014){
          wx.showToast({
            title: '图片含有违法违规内容',
            icon: 'none',
            mask: true
          });
          return;
        }else{
          // console.log('图片正常');
        }
      }
    })
    let fileList = this.data.fileList;
    fileList.push({
        url: file.url,
        name: Date.now(),
        isImage: true,
    })
    this.uploadToCloud();
    this.setData({
      fileList
    })
  },
  // 发布
  async handleSubmit(e){
    var that=this

    if(!this.data.topic||!this.data.content){
      wx.showToast({
        title: '标题和正文不能为空!',
        mask: true,
        icon: 'none'
      });
      return;
    }
    if(this.data.overtime=="请选择倒计时时间"){
      wx.showToast({
        title: '请选择结束时间!',
        mask: true,
        icon: 'none'
      });
      return;
    }
    if(this.data.overhours+this.data.overdays*24+this.data.overmonths*720<1){
      wx.showToast({
        title: '结束时间不得少于1小时!',
        mask: true,
        icon: 'none'
      });
      return;
    }
    // if(this.data.location==""){
    //   wx.showToast({
    //     title: '请选择位置信息!',
    //     mask: true,
    //     icon: 'none'
    //   });
    //   return;
    // }
    wx.showLoading({
      title: '发布中',
      showCancel: true,
      icon:'loading',
      mask:true
    })
    const {content,topic,fileList,indexs,location,selectDatas} = this.data;
    let res = await wx.cloud.callFunction({
      name: 'contentCheck',
      data: {
        msg: content+topic
      }
    })
    // console.log(res);
    if(res.result.msgR.errCode!==0){
      wx.showToast({
        title: '文字内容含有违法违规内容',
        icon: 'none',
        mask: true
      });
      return;
    }


    let userInfo = wx.getStorageSync('userInfo');
   wx.cloud.callFunction({
     name: 'postParty',
     data:{
        oName: userInfo.uName, 
        head_pic:userInfo.head_pic,
        partyContent: content,
        partyImg: fileList.length>0?fileList[0].url:'',
        partyOwner: userInfo._id,
        partyTopic: topic,
        partyType: selectDatas[indexs].title,
        pOverTime:that.data.overhours*3600+that.data.overdays*86400+that.data.overmonths*2592000,
        location:location
     }
   }).then(res=>{
      wx.hideLoading()
      wx.showToast({
        title: '发布成功',
        icon:'success'
      })
     console.log(res);
     wx.switchTab({
       url: '/pages/party/index',
     })
   })
  },
  // 上传文件到云
  uploadToCloud() { 

    const { fileList } = this.data;
    if (!fileList.length) {
      wx.showToast({ title: '请选择图片', icon: 'none' });
    } else {
      const uploadTasks = fileList.map((file, index) => this.uploadFilePromise(`my-photo${Date.now()}.png`, file));
      Promise.all(uploadTasks)
        .then(data => {
          // wx.showToast({ title: '上传成功', icon: 'none' });
          const fileList = data.map(item => ({ 
            url: item.fileID,
            name: Date.now(),
            isImage: true, }));
          this.setData({ cloudPath: data, fileList });
          console.log(data);
        })
        .catch(e => {
          wx.showToast({ title: '上传失败', icon: 'none' });
          console.log(e);
        });
    }
  },
  
  uploadFilePromise(fileName, chooseResult) {
    return wx.cloud.uploadFile({
      cloudPath: fileName,
      filePath: chooseResult.url
    });
  },

  // 图片上传
  handleUpdate(){
  },

  //图片删除
  handleDelImg(e){
    let fileList = this.data.fileList;
    fileList = fileList.filter((item,index)=>index!==e.detail.index);
    this.setData({
      fileList
    });
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})